package com.charmzenus.it.zuul.filter;

import com.charmzenus.it.zuul.base.BaseZuulFilter;
import com.charmzenus.it.zuul.constants.FitlerNumber;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

@Component
@RefreshScope
public class RateLimiterFilter extends BaseZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(RateLimiterFilter.class);


    @Value("${max_qps}")
    private String max_qps;

    // 每秒中，放100个令牌
    private RateLimiter RATE_LIMITER = null;

    @PostConstruct
    public void  init() {
        RATE_LIMITER = RateLimiter.create(Double.parseDouble(max_qps));
    }

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FitlerNumber.order_rate_limiter;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        if (!RATE_LIMITER.tryAcquire()) {
            // 如果没有拿到令牌
            logger.info("流量太大了");
            throw new RuntimeException();
        }
        return null;
    }
}
